package yu.code.yurpc.loadbalancer;

import yu.code.yurpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 轮询负载均衡
 */
public class RoundRobinLoadBalancer implements LoadBalancer {
    /**
     * 当前轮询下标
     */
    AtomicInteger currentIndex = new AtomicInteger(0);

    @Override
    public ServiceMetaInfo select(Map<String, Object> requestParams, List<ServiceMetaInfo> serviceMetaInfoList) {
        if(serviceMetaInfoList.isEmpty()){
            return null;
        }
        int size = serviceMetaInfoList.size();
        //只有一个服务，无需轮询
        if(size==1){
            return serviceMetaInfoList.get(0);
        }
        //取模选择
        return serviceMetaInfoList.get(currentIndex.getAndIncrement()%size);
    }
}
